<template>
  <div class="chat-container" :class="theme">
    <header class="chat-header">
      <button class="back-button" @click="goBack" aria-label="返回">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="19" y1="12" x2="5" y2="12"></line>
          <polyline points="12 19 5 12 12 5"></polyline>
        </svg>
      </button>
      <h1>{{ title }}</h1>
    </header>

    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="message in messages" 
        :key="message.id" 
        :class="['message', message.sender]"
      >
        <div class="message-content">
          <div class="message-text" v-html="renderMessageText(message.text)"></div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
      <div v-if="isTyping" class="message ai">
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input-container">
      <div class="input-wrapper">
        <input
          v-model="inputMessage"
          type="text"
          :placeholder="placeholder"
          @keyup.enter="sendMessage"
          :disabled="isSending"
          aria-label="输入消息"
        />
        <button 
          class="send-button" 
          @click="sendMessage" 
          :disabled="!inputMessage.trim() || isSending"
          aria-label="发送消息"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    default: '请输入消息...'
  },
  theme: {
    type: String,
    default: 'default'
  },
  apiUrl: {
    type: String,
    required: true
  },
  additionalParams: {
    type: Object,
    default: () => ({})
  },
  welcomeMessage: {
    type: String,
    default: '您好！有什么可以帮助您的吗？'
  },
  separateMessages: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['messageSent'])

const router = useRouter()
const messages = ref([])
const inputMessage = ref('')
const isSending = ref(false)
const isTyping = ref(false)
const eventSource = ref(null)
const messagesContainer = ref(null)
const chatId = ref('')
const currentAIMessageId = ref(null)

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
    // second: '2-digit' // 如果需要显示秒数可以取消注释
  })
}

// 渲染消息文本，正确处理转义字符
const renderMessageText = (text) => {
  if (!text) return ''
  
  // 创建一个临时元素来处理HTML转义
  const tempDiv = document.createElement('div')
  tempDiv.textContent = text
  let processedText = tempDiv.innerHTML
  
  // 将换行符转换为<br>标签
  processedText = processedText.replace(/\n/g, '<br>')
  
  // 处理多个连续空格
  processedText = processedText.replace(/ {2}/g, '&nbsp;&nbsp;')
  
  return processedText
}

// 返回主页
const goBack = () => {
  router.push('/')
}

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 生成唯一的chatId
const generateChatId = () => {
  return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 构建带参数的URL
const buildUrl = (message = null) => {
  const params = new URLSearchParams()
  
  // 添加额外参数
  Object.keys(props.additionalParams).forEach(key => {
    params.append(key, props.additionalParams[key])
  })
  
  // 如果有消息，添加消息参数
  if (message) {
    params.append('message', message)
    params.append('chatId', chatId.value)
  }
  
  const queryString = params.toString()
  return queryString ? `${props.apiUrl}?${queryString}` : props.apiUrl
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || isSending.value) return

  // 添加用户消息到界面
  const userMessage = {
    id: Date.now(),
    sender: 'user',
    text: message,
    timestamp: Date.now()
  }
  
  messages.value.push(userMessage)
  inputMessage.value = ''
  isSending.value = true
  isTyping.value = true
  scrollToBottom()

  try {
    // 发送消息到服务器（通过SSE参数）
    reconnectSSE(message)
    emit('messageSent', message)
  } catch (error) {
    console.error('发送消息失败:', error)
    handleError('发送消息失败')
  }
}

// 连接SSE
const connectSSE = () => {
  const url = buildUrl()
  eventSource.value = new EventSource(url)
  
  eventSource.value.onopen = () => {
    console.log('SSE连接已建立')
  }
  
  eventSource.value.onmessage = (event) => {
    isSending.value = false
    isTyping.value = false
    
    try {
      // 处理完成事件（空数据表示流结束）
      if (event.data === '' || event.data === '[DONE]') {
        currentAIMessageId.value = null
        handleConnectionComplete()
        return
      }
      
      // 解析数据
      let data
      if (typeof event.data === 'string') {
        try {
          data = JSON.parse(event.data)
        } catch (e) {
          // 如果不是JSON格式，直接使用原始数据
          data = { message: event.data }
        }
      } else {
        data = event.data
      }
      
      // 检查数据是否有效
      if (data && (data.message || data.content)) {
        const messageText = data.message || data.content
        
        // 如果separateMessages为true，每次响应都创建新的消息气泡
        if (props.separateMessages) {
          // 为每个响应创建新的消息气泡
          const aiMessage = {
            id: Date.now(),
            sender: 'ai',
            text: messageText,
            timestamp: Date.now()
          }
          messages.value.push(aiMessage)
          scrollToBottom()
        } else {
          // 如果还没有创建AI消息，创建一个新的
          if (!currentAIMessageId.value) {
            const aiMessage = {
              id: Date.now(),
              sender: 'ai',
              text: '',
              timestamp: Date.now()
            }
            messages.value.push(aiMessage)
            currentAIMessageId.value = aiMessage.id
          }
          
          // 找到当前AI消息并逐字拼接
          const aiMessageIndex = messages.value.findIndex(msg => msg.id === currentAIMessageId.value)
          if (aiMessageIndex !== -1) {
            messages.value[aiMessageIndex].text += messageText
            scrollToBottom()
          }
        }
      }
    } catch (error) {
      console.error('解析消息失败:', error)
      handleError('解析消息失败')
    }
  }
  
  eventSource.value.onerror = (error) => {
    console.error('SSE连接错误:', error)
    currentAIMessageId.value = null
    handleError('连接错误', true)
  }
}

// 重新连接SSE以发送新消息
const reconnectSSE = (message) => {
  if (eventSource.value) {
    eventSource.value.close()
  }
  
  const url = buildUrl(message)
  eventSource.value = new EventSource(url)
  
  eventSource.value.onmessage = (event) => {
    isSending.value = false
    isTyping.value = false
    
    try {
      // 处理完成事件（空数据表示流结束）
      if (event.data === '' || event.data === '[DONE]') {
        currentAIMessageId.value = null
        handleConnectionComplete()
        return
      }
      
      // 解析数据
      let data
      if (typeof event.data === 'string') {
        try {
          data = JSON.parse(event.data)
        } catch (e) {
          // 如果不是JSON格式，直接使用原始数据
          data = { message: event.data }
        }
      } else {
        data = event.data
      }
      
      // 检查数据是否有效
      if (data && (data.message || data.content)) {
        const messageText = data.message || data.content
        
        // 如果separateMessages为true，每次响应都创建新的消息气泡
        if (props.separateMessages) {
          // 为每个响应创建新的消息气泡
          const aiMessage = {
            id: Date.now(),
            sender: 'ai',
            text: messageText,
            timestamp: Date.now()
          }
          messages.value.push(aiMessage)
          scrollToBottom()
        } else {
          // 如果还没有创建AI消息，创建一个新的
          if (!currentAIMessageId.value) {
            const aiMessage = {
              id: Date.now(),
              sender: 'ai',
              text: '',
              timestamp: Date.now()
            }
            messages.value.push(aiMessage)
            currentAIMessageId.value = aiMessage.id
          }
          
          // 找到当前AI消息并逐字拼接
          const aiMessageIndex = messages.value.findIndex(msg => msg.id === currentAIMessageId.value)
          if (aiMessageIndex !== -1) {
            messages.value[aiMessageIndex].text += messageText
            scrollToBottom()
          }
        }
      }
    } catch (error) {
      console.error('解析消息失败:', error)
      handleError('解析消息失败')
    }
  }
  
  eventSource.value.onerror = (error) => {
    console.error('SSE连接错误:', error)
    isSending.value = false
    isTyping.value = false
    currentAIMessageId.value = null
    
    // 关闭连接
    if (eventSource.value) {
      eventSource.value.close()
      eventSource.value = null
    }
    
    // 只有在不是正常关闭的情况下才显示错误消息
    // 如果eventSource仍然存在，说明是异常断开
    // 我们已经在handleConnectionComplete中正确关闭了连接，所以这里不需要重复显示错误
  }
}

// 错误处理
const handleError = (errorMsg, showError = true) => {
  isSending.value = false
  isTyping.value = false
  currentAIMessageId.value = null
  
  // 关闭SSE连接
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
  
  // 只有在需要显示错误时才添加错误消息到聊天记录
  if (showError) {
    const errorMessage = {
      id: Date.now(),
      sender: 'system',
      text: errorMsg === '连接错误' ? '连接错误，请稍后重试' : `错误: ${errorMsg}`,
      timestamp: Date.now()
    }
    messages.value.push(errorMessage)
    scrollToBottom()
  }
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
})

// 组件挂载时初始化
onMounted(() => {
  // 生成唯一的chatId
  chatId.value = generateChatId()
  
  // 添加欢迎消息
  messages.value.push({
    id: Date.now(),
    sender: 'ai',
    text: props.welcomeMessage,
    timestamp: Date.now()
  })
  
  scrollToBottom()
})

// 组件卸载时清理
onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close()
  }
})

// 公共方法：添加消息
const addMessage = (message) => {
  messages.value.push(message)
  scrollToBottom()
}

// 公共方法：清除所有消息
const clearMessages = () => {
  messages.value = []
}

// 处理连接完成
const handleConnectionComplete = () => {
  isSending.value = false
  isTyping.value = false
  currentAIMessageId.value = null
  
  // 关闭SSE连接
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
  
  // 不显示错误消息
}

defineExpose({
  addMessage,
  clearMessages
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f1 100%);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.chat-container.psychologist {
  background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
}

.chat-container.super-agent {
  background: linear-gradient(135deg, #c2e9fb 0%, #a1c4fd 100%);
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  color: #333;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
}

.chat-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: inherit;
  filter: blur(20px);
  z-index: -1;
}

.chat-container.psychologist .chat-header {
  background: rgba(142, 197, 252, 0.85);
}

.chat-container.super-agent .chat-header {
  background: rgba(161, 196, 253, 0.85);
}

.back-button {
  background: none;
  border: none;
  color: #333;
  cursor: pointer;
  padding: 0.6rem;
  border-radius: 50%;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
  transform: scale(1.05);
}

.chat-header h1 {
  margin: 0;
  font-size: 1.3rem;
  font-weight: 600;
  letter-spacing: 0.3px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  background: transparent;
}

.message {
  display: flex;
  max-width: 85%;
  animation: fadeIn 0.3s ease-out;
}

.message.user {
  align-self: flex-end;
  justify-content: flex-end;
}

.message.ai {
  align-self: flex-start;
  justify-content: flex-start;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 100%;
}

.message.user .message-content {
  align-items: flex-end;
}

.message.ai .message-content {
  align-items: flex-start;
}

.message-text {
  padding: 1rem 1.4rem;
  border-radius: 22px;
  word-wrap: break-word;
  max-width: 100%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  line-height: 1.5;
  position: relative;
  font-size: 1rem;
}

.message.user .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 6px;
}

.chat-container.super-agent .message.user .message-text {
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
}

.message.ai .message-text {
  background: white;
  color: #333;
  border-bottom-left-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 0.7rem;
  color: rgba(0, 0, 0, 0.4);
  margin-top: 0.5rem;
  font-weight: 500;
}

.message.user .message-time {
  text-align: right;
  color: rgba(255, 255, 255, 0.8);
}

.message.ai .message-time {
  text-align: left;
}

.typing-indicator {
  display: flex;
  padding: 1rem 1.4rem;
  background: white;
  border-radius: 22px;
  border-bottom-left-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 10px;
  height: 10px;
  background-color: #999;
  border-radius: 50%;
  margin: 0 3px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.6;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input-container {
  padding: 1.2rem 1.5rem;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 30px;
  padding: 0.5rem 1.2rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.3s ease;
}

.input-wrapper:focus-within {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.input-wrapper input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 0.8rem 0.5rem;
  font-size: 1rem;
  outline: none;
  color: #333;
  font-family: inherit;
}

.input-wrapper input::placeholder {
  color: #aaa;
}

.input-wrapper input:disabled {
  opacity: 0.6;
}

.send-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.7rem;
  border-radius: 50%;
  transition: all 0.3s ease;
  color: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 0.5rem;
}

.chat-container.super-agent .send-button {
  color: #a1c4fd;
}

.send-button:hover:not(:disabled) {
  background-color: rgba(102, 126, 234, 0.1);
  transform: scale(1.1);
}

.chat-container.super-agent .send-button:hover:not(:disabled) {
  background-color: rgba(161, 196, 253, 0.1);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.send-button svg {
  width: 20px;
  height: 20px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
  margin: 1rem;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.25);
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    padding: 0.8rem 1.2rem;
  }
  
  .chat-header h1 {
    font-size: 1.2rem;
  }
  
  .chat-messages {
    padding: 1rem;
    gap: 1rem;
  }
  
  .message {
    max-width: 90%;
  }
  
  .message-text {
    padding: 0.8rem 1.2rem;
    font-size: 0.95rem;
  }
  
  .chat-input-container {
    padding: 1rem;
  }
  
  .input-wrapper {
    padding: 0.4rem 1rem;
  }
  
  .input-wrapper input {
    padding: 0.7rem 0.4rem;
    font-size: 0.95rem;
  }
}

@media (max-width: 480px) {
  .chat-header {
    padding: 0.7rem 1rem;
  }
  
  .chat-header h1 {
    font-size: 1.1rem;
  }
  
  .back-button {
    padding: 0.5rem;
  }
  
  .chat-messages {
    padding: 0.8rem;
    gap: 0.8rem;
  }
  
  .message {
    max-width: 95%;
  }
  
  .message-text {
    padding: 0.7rem 1rem;
    font-size: 0.9rem;
    border-radius: 18px;
  }
  
  .chat-input-container {
    padding: 0.8rem;
  }
  
  .input-wrapper {
    padding: 0.3rem 0.8rem;
  }
  
  .input-wrapper input {
    padding: 0.6rem 0.3rem;
    font-size: 0.9rem;
  }
  
  .send-button {
    padding: 0.6rem;
  }
  
  .send-button svg {
    width: 18px;
    height: 18px;
  }
}
</style>